from typing import Dict, Any, Optional
import time

class CacheService:
    def __init__(self, default_ttl: int = 300):  # 默认缓存5分钟
        self._cache: Dict[str, Dict[str, Any]] = {}
        self._default_ttl = default_ttl

    def get(self, key: str) -> Optional[Any]:
        """获取缓存数据"""
        if key not in self._cache:
            return None
        
        cache_data = self._cache[key]
        if time.time() > cache_data['expire_time']:
            # 缓存已过期，删除并返回None
            del self._cache[key]
            return None
            
        return cache_data['value']

    def set(self, key: str, value: Any, ttl: Optional[int] = None) -> None:
        """设置缓存数据"""
        expire_time = time.time() + (ttl or self._default_ttl)
        self._cache[key] = {
            'value': value,
            'expire_time': expire_time
        }

    def delete(self, key: str) -> None:
        """删除缓存数据"""
        if key in self._cache:
            del self._cache[key]

    def clear(self) -> None:
        """清空所有缓存"""
        self._cache.clear()

    def cleanup_expired(self) -> None:
        """清理过期缓存"""
        current_time = time.time()
        expired_keys = [
            key for key, data in self._cache.items()
            if current_time > data['expire_time']
        ]
        for key in expired_keys:
            del self._cache[key] 